// Copyright (c) 2024, lanlian and contributors
// For license information, please see license.txt

frappe.ui.form.on("EMS Maintenance Plan", {
	refresh(frm) {
        // 点检方案下推点检单
        frm.add_custom_button(__('Make EMS Maintenance Doc'), () => {
            frappe.model.open_mapped_doc({
                method: "ems.equipment_managerment_system.doctype.ems_maintenance_plan.ems_maintenance_plan.make_maintenance_doc",
                frm: cur_frm,
                freeze_message: __("Creating Task ...")
            });
        });
        // 从指定的点检模版复制点检项目,逐行添加至子表
        frm.fields_dict["items"].grid.add_custom_button(__('Get From Template'), 
			function() {
                frappe.db.get_doc('EMS Maintenance Plan Template', frm.doc.template_title)
                .then(doc => {
                    doc.items.forEach(item => {
                        frm.add_child('items', {
                            maintenance_item: item.maintenance_item,
                            description: item.description,
                            maintenance_method: item.maintenance_method,
                            maintenance_tool: item.maintenance_tool,
                            replacement_part: item.replacement_part,
                            maintenance_category: item.maintenance_category
                        });
                    });
                    doc.part_items.forEach(item => {
                        frm.add_child('part_items', {
                            item_code: item.item_code,
                            item_name: item.item_name,
                            description: item.description,
                            uom: item.uom,
                            qty: item.qty,
                            item_group: item.item_group,
                            price_no_tax: item.price_no_tax,
                            amount_no_tax: item.amount_no_tax,
                        });
                    });
                    frm.doc.maintenance_plan = doc.template_title;
                    frm.doc.maintenance_category = doc.maintenance_category;
                    frm.doc.periodicity = doc.periodicity;
                })
                .then( () => { frm.refresh_fields();
                    // frm.refresh_field('items');frm.refresh_field('part_items');frm.refresh_field('periodicity');
                })
        });
        frm.fields_dict["items"].grid.grid_buttons.find('.btn-custom').removeClass('btn-default').addClass('btn-primary');
	},
});
